// 自定义hooks-useTimeout

import { useEffect, useRef } from "react";

type Callback = () => void;
function useTimeout(callback: Callback, delay?: number) {
  const memorized = useRef<Callback>();

  useEffect(() => {
    memorized.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!delay || delay < 0) return;

    const timer = setTimeout(() => {
      if (memorized.current !== undefined) {
        memorized.current();
      }
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [delay]);
}

export default useTimeout;
